<template>
  <ArtTableFullScreen>
    <div class="dict-page" id="table-full-screen" :style="{ height: containerMinHeight}">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
        :showExpand="false"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 220px);">
        <!-- 表格头部 -->
        <ArtTableHeader :showZebra="false" v-model:columns="columnChecks" @refresh="handleRefresh">
          <template #left>
            <!-- 按钮权限：后端控制模式，使用自定义指令 -->
            <ElButton @click="openDialog('add', '-1')" v-ripple>
              添加字典
            </ElButton>
            <ElButton @click="toggleExpand" v-ripple>
              {{ isExpanded ? '收起' : '展开' }}
            </ElButton>
          </template>
        </ArtTableHeader>
		
		<div style="height: calc(100% - 35px);">
			<!-- 表格 -->
			<ArtTable
			  rowKey="id"
			  ref="tableRef"
			  :loading="loading"
			  :data="tableData"
			  :marginTop="10"
			  :stripe="false"
			>
			  <template #default>
				<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
			  </template>
			</ArtTable>
		</div>
        <ElDialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal='false' :draggable='true' width="700px" align-center>
          <ElForm ref="formRef" :model="form" :rules="rules" label-width="85px">
			<ElFormItem label="中文名称" prop="cnName">
			  <ElInput v-model="form.cnName" placeholder="中文名称"></ElInput>
			</ElFormItem>
			<ElFormItem label="英文名称" prop="enName">
			  <ElInput v-model="form.enName" placeholder="英文名称"></ElInput>
			</ElFormItem>
			<ElFormItem label="字典代码" prop="code">
			  <ElInput v-model="form.code" placeholder="字典代码"></ElInput>
			</ElFormItem>
			<ElFormItem label="字典排序" prop="sort" style="width: 100%">
			  <ElInputNumber
			    v-model="form.sort"
			    style="width: 100%"
			    @change="handleChange"
			    :min="1"
			    controls-position="right"
			  />
			</ElFormItem>
			<ElFormItem label="备注" prop="remark">
			  <ElInput v-model="form.remark" type="textarea" :rows="3" />
			</ElFormItem>
		  </ElForm>

          <template #footer>
            <span class="dialog-footer">
              <ElButton @click="dialogVisible = false">取 消</ElButton>
              <ElButton type="primary" @click="submitForm()">确 定</ElButton>
            </span>
          </template>
        </ElDialog>
		
		<!--字典项编辑表格-->
		<ElDialog :title="dialogDictItemTitle" v-model="dialogDictItemVisible" :close-on-click-modal='false' :draggable='true' @close="closedDialogDictItem" width="50%" align-center>

			<div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
			  <el-button type="primary" @click="handleAdd">新增</el-button>
			  <!-- <el-button type="success" @click="handleSaveAll">保存所有</el-button> -->
			</div>
			
			<el-table 
			      :data="tableItemData" 
			      border 
			      stripe
			      style="width: 100%"
			    >
			      <el-table-column prop="cnLabel" label="中文标签" width="180">
			        <template #default="{ row }">
			          <el-input 
			            v-if="row.editing" 
			            v-model="row.cnLabel" 
			            placeholder="请输入中文标签"
			          />
			          <span v-else>{{ row.cnLabel }}</span>
			        </template>
			      </el-table-column>
			      
			      <el-table-column prop="enLabel" label="英文标签" width="180">
			        <template #default="{ row }">
			          <el-input 
			            v-if="row.editing" 
			            v-model="row.enLabel" 
			            placeholder="请输入英文标签"
			          />
			          <span v-else>{{ row.enLabel }}</span>
			        </template>
			      </el-table-column>
			      
			      <el-table-column prop="value" label="值">
			        <template #default="{ row }">
			          <el-input 
			            v-if="row.editing" 
			            v-model="row.value" 
			            placeholder="请输入值"
			          />
			          <span v-else>{{ row.value }}</span>
			        </template>
			      </el-table-column>
			      
			      <el-table-column prop="sort" label="序号" width="160" align="center">
			        <template #default="{ row }">
			          <el-input-number 
			            v-if="row.editing" 
			            v-model="row.sort" 
			            :min="1" 
			            :max="999"
			            controls-position="right"
			            size="small"
			          />
			          <span v-else>{{ row.sort }}</span>
			        </template>
			      </el-table-column>
			      
			      <el-table-column prop="remark" label="备注">
			        <template #default="{ row }">
			          <el-input 
			            v-if="row.editing" 
			            v-model="row.remark" 
			            type="textarea"
			            :autosize="{ minRows: 1, maxRows: 3 }"
			            placeholder="请输入备注"
			          />
			          <span v-else>{{ row.remark }}</span>
			        </template>
			      </el-table-column>
			      
			      <el-table-column fixed="right" label="操作" width="180" align="center">
			        <template #default="{ row, $index }">
			          <template v-if="row.editing">
			            <el-button 
			              size="small" 
			              type="success" 
			              @click="handleSave(row)"
			            >
			              保存
			            </el-button>
			            <el-button 
			              size="small" 
			              @click="handleCancel(row, $index)"
			            >
			              取消
			            </el-button>
			          </template>
			          <template v-else>
			            <el-button 
			              size="small" 
			              type="primary" 
			              @click="handleEdit(row)"
			            >
			              编辑
			            </el-button>
			            <el-button 
			              size="small" 
			              type="danger" 
			              @click="handleDelete(row,$index)"
			            >
			              删除
			            </el-button>
			          </template>
			        </template>
			      </el-table-column>
			    </el-table>
		</ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { IconTypeEnum } from '@/enums/appEnum'
  import { formatMenuTitle } from '@/router/utils/utils'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { ElPopover, ElButton } from 'element-plus'
  import { AppRouteRecord } from '@/types/router'
  import { useAuth } from '@/composables/useAuth'
  import { SearchFormItem } from '@/types'
  import { DictService } from '@/api/sys/dictApi'
  import dayjs from 'dayjs';
  import { useCommon } from '@/composables/useCommon'
  const { containerMinHeight } = useCommon()
  defineOptions({ name: 'Dict' })
  const { hasAuth } = useAuth()
  const loading = ref(false)

  // 定义表单搜索初始值
  const initialSearchState = {
    cnName: '',
    enName: '',
	code:''
  }

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  // 增加实际应用的搜索条件状态
  const appliedFilters = reactive({ ...initialSearchState })

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    Object.assign(appliedFilters, { ...initialSearchState })
    getTableData()
  }

  // 搜索处理
  const handleSearch = () => {
    // 将当前输入的筛选条件应用到实际搜索
    Object.assign(appliedFilters, { ...formFilters })
    getTableData()
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '中文名称',
      prop: 'cnName',
      type: 'input',
      config: {
        clearable: true
      }
    },
    {
      label: '英文名称',
      prop: 'enName',
      type: 'input',
      config: {
        clearable: true
      }
    },
    {
      label: '字典代码',
      prop: 'code',
      type: 'input',
      config: {
        clearable: true
      }
    }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'cnName',
      label: '中文名称',
      minWidth: 120,
    },
	{
	  prop: 'enName',
	  label: '英文名称',
	  minWidth: 120,
	},
	{
	  prop: 'code',
	  label: '字典代码',
	  minWidth: 100
	},
    {
      prop: 'remark',
      label: '备注'
    },
    {
      prop: 'modifyTime',
      label: '编辑时间',
      formatter: (row:any) => {
      		return dayjs(row.modifyTime).format('YYYY-MM-DD HH:MM:ss')
      }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 280,
      formatter: (row: any) => {
        return h('div', [
            h(ArtButtonTable, {
              type: 'add',
              onClick: () => openDialog('add',row.id)
            }),
			h(ArtButtonTable, {
			  icon: '&#xe7ae;',
			  iconColor:'#5D87FF',
			  onClick: () => openItemTableDialog(row)
			}),
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => openDialog('edit',row.parentId,row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => deleteRow(row)
            })
        ])
      }
    }
  ])

  const handleRefresh = () => {
    getTableData()
  }

  const dialogVisible = ref(false)
  const form = reactive({
	id: '',
	parentId:'-1',
    cnName: '',
	enName: '',
    code: '',
    remark: '',
    sort: 1,
  })
  const iconType = ref(IconTypeEnum.UNICODE)

  const rules = reactive<FormRules>({
    cnName: [
      { required: true, message: '请输入中文名称', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
	enName: [
	  { required: true, message: '请输入英文名称', trigger: 'blur' },
	  { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
	],
    code: [{ required: true, message: '请输入字典代码', trigger: 'blur' }],
  })

  const tableData = ref<any[]>([])

  onMounted(() => {
    getTableData()
  })

  const getTableData = async () => {
    loading.value = true
  	const data = await DictService.getLoadAll({
		query:formFilters
	});
  	tableData.value =data;
  	loading.value = false
  }
  
  const formRef = ref<FormInstance>()
  const dialogTitle = ref<string>()

  const handleChange = () => {}

  const submitForm = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
			loading.value = true
			const data = await DictService.save(form);
			form.id=data.id;
			ElMessage.success(`成功`)
			getTableData();
			dialogVisible.value = false
        } catch {
			ElMessage.error(`失败`)
        }finally{
			loading.value = false
		}
      }
    })
  }

  const openDialog = (type: string,parentId:string, row?: any) => {
    dialogVisible.value = true
    resetForm()
	if('add'==type){
		dialogTitle.value='新增字典'
	}else{
		dialogTitle.value='编辑字典'
	}
	form.id = row?.id||''
	form.parentId = parentId ||'-1'
	form.cnName = row?.cnName||''
	form.enName = row?.enName||''
	form.code = row?.code||''
	form.remark = row?.remark || ''
	form.sort = row?.sort || 1
	
  }

	const resetForm = () => {
		formRef.value?.resetFields()
		Object.assign(form, {
			id: '',
			parentId:'-1',
			cnName: '',
			enName: '',
			code: '',
			remark: '',
			sort: 1,
		})
	}

  const deleteRow = async (row:any) => {
    try {
      await ElMessageBox.confirm('确定要删除该'+row.cnName+'及其包含的所有信息吗？删除后24小时内可恢复.', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
		loading.value = true
  		try {
  			await DictService.delete(row.id);
  			 ElMessage.success('删除成功')
  			getTableData();
  		} catch {
  			ElMessage.error(`失败`)
  		}finally{
  			dialogVisible.value = false
			loading.value = false
  		}
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
  
  const isExpanded = ref(false)
  const tableRef = ref()

  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value[isExpanded.value ? 'expandAll' : 'collapseAll']()
      }
    })
  }
  
  // 字典项编辑表格
  const dialogDictItemTitle = ref<string>('')
  const dialogDictItemVisible = ref<boolean>(false)
  const tableItemData = ref<any[]>([])
  const isEditItem=ref<boolean>(false);
  const associationDict=ref<string>('');
  
  const openItemTableDialog= async (row:any)=>{
	  dialogDictItemTitle.value=row.cnName+'项';
	  dialogDictItemVisible.value=true;
	  loading.value = true
	  associationDict.value=row.id
	  try{
		 const data = await DictService.getItemPages({
		 	query:{
				dictId:row.id
			}
		 });
		 tableItemData.value =data||[];
	  }catch(e:any){
		  console.error(e)
	  }finally{
		  loading.value = false 
	  }
  }
  
	// 唯一ID生成器
	let nextId = ref(tableItemData.value.length + 1);

	// 新增行
	const handleAdd = () => {
	  tableItemData.value.unshift({
		id: nextId.value++,
		cnLabel: '',
		enLabel: '',
		value: '',
		sort: tableItemData.value.length + 1,
		remark: '',
		editing: true,
		originalData: null
	  });
	  
	  isEditItem.value=false;
	  
	};

	// 编辑行
	const handleEdit = (row:any) => {
	  // 保存原始数据用于取消操作
	  isEditItem.value=true;
	  row.originalData = { ...row };
	  row.editing = true;
	};

	// 保存单行
	const handleSave = async (row:any) => {
	  // 表单验证
	  if (!row.cnLabel) {
		ElMessage.warning('中文标签不能为空');
		return;
	  }
	  if (!row.enLabel) {
		ElMessage.warning('英文标签不能为空');
		return;
	  }
	  loading.value = true
	  try {
		  
		if(isEditItem.value==false ) {
			row.id='';
			row.dictId=associationDict.value;
		}
	  	const data = await DictService.saveItem(row);
	  	row.id=data.id;
	  	ElMessage.success(`成功`)
		row.editing = false;
		row.originalData = null;
		isEditItem.value=false;
	  } catch {
	  	ElMessage.error(`失败`)
	  }finally{
		  loading.value = false
	  }
	};

	// 取消编辑
	const handleCancel = (row:any, index:any) => {
	  if (row.originalData) {
		// 恢复原始数据
		Object.assign(row, row.originalData);
		row.editing = false;
		row.originalData = null;
		isEditItem.value=false;
	  } else {
		// 如果是新增行，直接删除
		tableItemData.value.splice(index, 1);
	  }
	};

	// 删除行
	const handleDelete = async (row:any,index:any) => {
	  try {
	    await ElMessageBox.confirm('确定要删除该'+row.cnLabel+'信息吗？删除后24小时内恢复.', '提示', {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'warning'
	    })
	  	loading.value = true
	  	try {
	  		await DictService.deleteItem(row.id);
			tableItemData.value.splice(index, 1);
	  		ElMessage.success('删除成功')
	  	} catch {
	  		ElMessage.error(`失败`)
	  	}finally{
			loading.value = false
	  	}
	  } catch (error) {
	    if (error !== 'cancel') {
	      ElMessage.error('删除失败')
	    }
	  }
	};

	// 保存所有数据
	const handleSaveAll = () => {
	  // 验证所有编辑中的数据
	  const editingRows = tableItemData.value.filter(row => row.editing);
	  
	  if (editingRows.length > 0) {
		ElMessage.warning('请先保存所有编辑中的数据');
		return;
	  }
	  
	  // 验证数据完整性
	  const invalidRows = tableItemData.value.filter(row => 
		!row.cnName || !row.enName || !row.value
	  );
	  
	  if (invalidRows.length > 0) {
		ElMessage.error('请完善所有必填项数据');
		return;
	  }
	  
	  // 实际项目中这里调用API保存数据
	  console.log('所有数据:', JSON.parse(JSON.stringify(tableItemData.value)));
	  ElMessage.success('所有数据保存成功');
	};
  
	const closedDialogDictItem=()=>{
		associationDict.value='';
	}
  
</script>

<style lang="scss" scoped>
  .dict-page {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }

    :deep(.small-btn) {
      height: 30px !important;
      padding: 0 10px !important;
      font-size: 12px !important;
    }
  }
</style>
